import { ElMessage } from 'element-plus'

export default {
  mounted(el, binding) {
    el.addEventListener('contextmenu', function(event) { // 使用函数声明而非箭头函数
      event.preventDefault()
      const text = binding.value || el.textContent.trim()
      if (!text) return

      // 创建右键菜单
      const menu = document.createElement('div')
      menu.style.position = 'fixed'
      menu.style.background = '#fff'
      menu.style.boxShadow = '0 2px 12px 0 rgba(0, 0, 0, 0.1)'
      menu.style.borderRadius = '4px'
      menu.style.padding = '6px 0'
      menu.style.zIndex = '9999'
      menu.style.minWidth = '120px'

      // 添加复制选项
      const copyItem = document.createElement('div')
      copyItem.style.padding = '8px 16px'
      copyItem.style.cursor = 'pointer'
      copyItem.textContent = '复制'
      copyItem.addEventListener('click', () => copyText(text))

      copyItem.addEventListener('mouseenter', () => {
        copyItem.style.background = '#f5f7fa'
      })
      copyItem.addEventListener('mouseleave', () => {
        copyItem.style.background = ''
      })

      menu.appendChild(copyItem)
      document.body.appendChild(menu)

      // 定位菜单
      menu.style.left = `${e.clientX}px`
      menu.style.top = `${e.clientY}px`

      // 点击其他地方关闭菜单
      const closeMenu = () => {
        document.body.removeChild(menu)
        document.removeEventListener('click', closeMenu)
      }
      setTimeout(() => {
        document.addEventListener('click', closeMenu)
      }, 100)
    })

    // 添加悬停样式
    el.style.cursor = 'context-menu'
  }
}

async function copyText(text) {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('复制成功')
  } catch (err) {
    const textarea = document.createElement('textarea')
    textarea.value = text
    document.body.appendChild(textarea)
    textarea.select()
    document.execCommand('copy')
    document.body.removeChild(textarea)
    ElMessage.success('复制成功')
  }
}
